<template>
  <div class="userInfo" @mousemove="handleMouseMove($event)">
    <div class="img"><img class="img-top" :style="{'transform':translate,'width':info_imgStyle,}" src="@/assets/userInfo-top.jpg" alt="个人中心顶部图片"></div>
    <div class="info" :style="info_style">
      <el-card class="box-card">
        <el-upload
          class="avatar-uploader"
          action="api/admin/common/upload"
          :auto-upload="true"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl != null ? imageUrl : process.env.VUE_APP_AVATAR" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          <div class="avatar-msg">更改头像</div>
        </el-upload>
        <div class="userinfo">
          <div class="title">用户信息</div>
          <div class="userinfo-descriptions">
            <span>&nbsp;&nbsp;用&nbsp;户&nbsp;名&nbsp;:&nbsp;&nbsp;</span>
              <el-input style="width: 80%; "
                placeholder="空"
                :value="userInfo.username"
                :disabled="true">
              </el-input><br>
            <span>真实姓名&nbsp;:&nbsp;&nbsp;</span>
            <el-input style="width: 80%;"
                placeholder="空"
                :value="userInfo.name"
                :disabled="true">
              </el-input><br>
            <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;性&nbsp;别&nbsp;:&nbsp;&nbsp;</span>
            <el-input style="width: 80%;"
                placeholder="空"
                :value="sex"
                :disabled="true">
              </el-input><br>
            <span>&nbsp;&nbsp;手&nbsp;机&nbsp;号&nbsp;:&nbsp;&nbsp;</span>
            <el-input style="width: 80%;"
                placeholder="空"
                :value="userInfo.phone"
                :disabled="true">
              </el-input><br>
            <span>身份证号&nbsp;:&nbsp;&nbsp;</span>
            <el-input style="width: 80%;"
                placeholder="空"
                :value="userInfo.idNumber"
                :disabled="true">
              </el-input><br>
            <span>入职时间&nbsp;:&nbsp;&nbsp;</span>
            <el-input style="width: 80%;"
                placeholder="空"
                :value="createTime"
                :disabled="true">
              </el-input>
          </div>
          <!-- {{ screenWidth }}，{{ screenWebWidth }}，{{ screenHeight }}，{{ screenWebHeight }} -->
        </div>
        <div class = "button">
          <el-button type="primary" @click="updateInfo()">修改信息</el-button>
          <el-button type="primary" @click="updatePassword()">修改密码</el-button>
        </div>
        <el-dialog title="个人信息" :visible.sync="dialogFormVisible">
          <el-form :model="userInfo2" :rules="Rules">
            <el-form-item label="用户名" :label-width="formLabelWidth">
              <el-input v-model="userInfo2.username" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="姓名" :label-width="formLabelWidth">
              <el-input v-model="userInfo2.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="性别" :label-width="formLabelWidth" style="text-align:left">
              <el-radio v-model="userInfo2.sex" :label="0">男</el-radio>
              <el-radio v-model="userInfo2.sex" :label="1">女</el-radio>
            </el-form-item>
            <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
              <el-input v-model="userInfo2.phone" autocomplete="off" type="number" oninput="if(value.length>11)value=value.slice(0,11)" onkeyup="this.value = this.value.replace(/[^\d]/g,'');"></el-input>
            </el-form-item>
            <el-form-item label="身份证" :label-width="formLabelWidth" prop="idNumber">
              <el-input v-model="userInfo2.idNumber" autocomplete="off" type="number" oninput="if(value.length>18)value=value.slice(0,18)"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="sumbitUpdate()">确 定</el-button>
          </div>
        </el-dialog>
        <el-dialog title="修改密码" :visible.sync="dialogFormVisible2">
          <el-form :model="passForm" status-icon :rules="Rules" ref="passForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="旧密码" prop="Oldpass">
              <el-input type="password" v-model="passForm.Oldpass" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="pass">
              <el-input type="password" v-model="passForm.pass" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPass">
              <el-input type="password" v-model="passForm.checkPass" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item style="text-align: center;">
              <el-button type="primary" @click="submitForm()">提交</el-button>
              <el-button @click="cancel()">取消</el-button>
            </el-form-item>
          </el-form>

        </el-dialog>
        <!-- 鼠标位置：{{ mouse.x }}, {{ mouse.y }},{{ X }},{{ Y }} -->
      </el-card>
    </div>
  </div>
</template>

<script>
import {queryById,updateUser,updatePassword} from '@/api/user'
export default {
    data() {
        var checkPhone = (rule, value, callback) => { // 手机号验证
            if (!value) {
              return callback(new Error('手机号不能为空'));
            } else {
              const reg = /^1[3456789]\d{9}$/
              if (reg.test(value)) {
                callback();
              } else {
                return callback(new Error('请输入正确的手机号'));
              }
            }
          };
          var checkIdNumber = (rule, value, callback) => { // 手机号验证
            if (!value) {
              return callback(new Error('身份证号不能为空'));
            } else {
              const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
              if (reg.test(value)) {
                callback();
              } else {
                return callback(new Error('请输入正确的身份证号'));
              }
            }
          };
          var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.ruleForm.checkPass !== '') {
            this.$refs.ruleForm.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm.pass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
        return {
            Rules:{
              phone: [
                { required: true, message: "请输入正确手机号", trigger: "blur" },
                {validator: checkPhone, trigger: 'blur'}
              ],
              idNumber:[
                { required: true, message: "请输入正确身份证号", trigger: "blur" },
                {validator: checkIdNumber, trigger: 'blur'}
              ],
              pass: [
                { validator: validatePass, trigger: 'blur' }
              ],
              checkPass: [
                { validator: validatePass2, trigger: 'blur' }
              ],
            },
            passForm: {
              Oldpass:'',
              pass: '',
              checkPass: '',
            },
            image_top:'@/assets/img_denglu_bj.jpg',
            image_top2:'@/assets/userInfo-top.jpg',
            mouseX: 0,
            mouseY: 0,
            X:0,
            Y:0,
            translate:'translate(0, 0)', //960.5 540.5
            mouse:{
              x:0,
              y:0
            },
            userInfo:null,
            userInfo2:null,
            sex:'',
            sex2:0,
            createTime:'',
            imageUrl: this.$store.state.user.userInfo.avatar,
            dialogFormVisible: false,
            dialogFormVisible2: false,
            formLabelWidth: '120px',
            screenWidth: document.body.clientWidth, //获取屏幕宽度
            screenWebWidth:document.documentElement.clientWidth, //获取页面宽度
            screenHeight: document.body.clientHeight, //获取屏幕高度
            screenWebHeight:document.documentElement.clientHeight, //获取页面高度
            info_left_width:0,
            info_left_height:0,
            info_style:'',
            info_imgStyle:''
        }
    },
    created(){
      const that = this
      const res =queryById(that.$store.state.user.userInfo.id);
      res.then((res)=>{
        that.userInfo = res.data
        console.log(res.data)
        that.userInfo2 = JSON.parse(JSON.stringify(res.data));
        that.sex = that.userInfo.sex == 0?'男':'女'
        that.createTime = that.userInfo.createTime.split(' ')[0]
      })

      //info位置
      this.info_left_width = document.documentElement.clientWidth*0.0316
      this.info_left_height = document.documentElement.clientHeight/9
      this.info_style = 'left:' + this.info_left_width +'px;'

      //info图片大小
      const imgSize = document.documentElement.clientWidth+80;
      this.info_imgStyle =  imgSize + 'px;'
    },
    methods:{
      handleMouseMove(event) { //获取鼠标位置
        this.mouse.x = event.clientX;
        this.mouse.y = event.clientY;
        this.X = (this.mouse.x-960.5)/90;
        this.Y = (this.mouse.y-540.5)/80;
        this.imgeMove(this.X,this.Y)
    },
      imgeMove(x,y){
        const t1 = 'translate('
        this.translate = t1 + x +'px' + ',' + y + 'px)'
      },
      //图片上传
      handleAvatarSuccess(res, file) {
        // console.log(this.imageUrl)
        this.imageUrl = res.data;
        console.log(this.imageUrl)
        
      },
      beforeAvatarUpload(file) {
        console.log("beforeUpload",file)
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        // const isJPG = file.type === 'image/jpeg';
        const isLt20M = file.size / 1024 / 1024 < 20;

        if (!isJPG&&!isPNG) {
          this.$message.error('上传头像图片只能是 JPG和PNG 格式!');
        }
        if (!isLt20M) {
          this.$message.error('上传头像图片大小不能超过 20MB!');
        }
        console.log((isJPG || isPNG) && isLt20M)
        return (isJPG || isPNG) && isLt20M;
      },
      base64ImgtoFile (dataurl, filename = 'file') {
      const arr = dataurl.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const suffix = mime.split('/')[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime
      })
    },
    updateInfo(){
      this.dialogFormVisible = true
      this.userInfo2 = JSON.parse(JSON.stringify(this.userInfo))
      this.userInfo2.avatar = this.imageUrl
      // console.log('this.userInfo.avatar'+this.userInfo.avatar)
      // console.log('this.imageUrl'+this.imageUrl)
    },
    updatePassword(){
      this.dialogFormVisible2 = true
    },
    sumbitUpdate(){
      const that = this
      const res = updateUser(this.userInfo2)
      res.then((res)=>{
        that.$message({
          message: '修改成功',
          type: 'success'
        });
        that.userInfo = JSON.parse(JSON.stringify(this.userInfo2))
        that.sex = that.userInfo.sex == 0? '男':'女'
        //改全局参数
        const token = that.$store.state.user.userInfo.token 
        that.$store.state.user.userInfo = that.userInfo
        that.$store.state.user.userInfo.token = token
        this.dialogFormVisible = false
        console.log(res)
      }).catch((err)=>{
        that.$message.error('修改失败');
        console.log(err)
      })
      
    },
    //修改密码
    submitForm(){
      const that = this
      console.log(that.passForm)
      const res = updatePassword(that.$store.state.user.userInfo.id,that.passForm.Oldpass,that.passForm.pass)
      res.then((res)=>{
        console.log(res)
        that.$message({
          message: '修改成功',
          type: 'success'
        });
        this.dialogFormVisible2 = false
      }).catch((err)=>{
        that.$message.error(err);
        console.log(err)
      })
    },
    cancel(){
      this.dialogFormVisible2 = false;
      this.passForm.Oldpass = '';
      this.passForm.checkPass = '';
      this.passForm.pass = '';
    }
    },
    watch:{// item1为新值，item2为旧值

    }
}
</script>

<style scoped>

.img{
  margin-top: 20px;
  border-radius: 10px;
  height: 350px;
  /* width: 1600px; */
  width: calc(100%);
  /* border-color: aqua;
  border-style: solid; */
  overflow: hidden;
}

.img-top{
  /* margin-top: 30px; */
  border-radius: 10px;
  height: 380px;
  /* width: 1680px; */
  width: 1680px;
  /* width: fit-content; */
  object-fit: cover;
  position: relative;
  left: -10px;
  top: -10px;
}

.text {
    font-size: 14px;
  }

  .item {
    padding: 18px 0;
  }

  .info{
    /* position: absolute;
    left: 300px;
    top: 350px; */
    position: relative;
    /* 0.0316 */
    /* left: 48px;  */
    top: -110px;

  }

  .box-card {
    height: 100%;
    /* width: 1500px; */
    width: 92%;

  }

  .avatar-img{
    border-radius: 50%;
    height: 180px;
    width: 180px;
    object-fit: cover;
    position: absolute;
    left: 80px;
    top: -80px;
  }
  .avatar-msg{
    display: none;
    position: absolute;
    left: 42px;
    top: 16px;
    color: #fffefe;
    font-size: 22px;
  }
  .avatar-uploader:hover{
    transform: scale(1.2);
    animation: la 0.5s ;

  }

  .avatar-uploader:hover .avatar{
    filter: blur(10px);
  -webkit-filter: blur(1px);
  }

  .avatar-uploader:hover .avatar-msg{
    display:block;
    /* transform: scale(1.2);
    animation: la 0.5s ; */
  }


  @keyframes la {
    0% {
        transform:  scale(1.0);
    }

    100% {
        transform:  scale(1.2);
    }
}
.avatar-uploader{
  border-radius: 50%;
    height: 180px;
    width: 180px;
    object-fit: cover;
    position: absolute;
    left: 80px;
    top: -80px;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: cover;
    border-radius: 5px;
  }

  .userinfo{
    /* height: 300px; */
    
    
  }

  .userinfo-descriptions{
    /* display: flex;
    flex-direction: column;
    justify-content: flex-start; */
    /* height: 300px; */
    line-height: 80px;

  }

  .title{
    font-weight:bolder;
    font-size: 24px;
    line-height: 160px;
    /* color: #7b2b2b; */
  }

  .button{
    line-height: 160px;
  }

  ::v-deep .userinfo-descriptions .el-input__inner{
    color: #454242;
    font-size:16px;
  }


</style>